<template>
  <div class="app-container">
    <Pagetitle
      :title="pageTitle.title"
      :name="pageTitle.name"
      :btnName="pageTitle.btnName"
      @btnFun="btnFun"
    ></Pagetitle>
    <div class="filter-container">

    </div>
    <div class="table-container min-height">
      <Form
        ref="addTaskForm"
        :model="addTaskForm"
      >
        <Row
          :gutter="8"
          type="flex"
          justify="start"
        >
          <Col
            :md="12"
            :xs="24"
            :lg="10"
            class="entery-top"
          >
          <span>成本中心</span>
          <FormItem
            prop="costCenterId"
            :rules="{required: true,type:'number',message:'选择成本中心',trigger: 'change'}"
          >
            <Select
              v-model="addTaskForm.costCenterId"
              placeholder="选择成本中心"
              class="min-width"
            >
              <template v-for="(brand,index) in costCenterSelect">
                <Option
                  :key="index"
                  :value="brand.costId"
                >{{brand.costCenterName}}</Option>
              </template>
            </Select>
          </FormItem>

          </Col>
          <Col
            :md="12"
            :xs="24"
            :lg="10"
            class="entery-top"
          >
          <span>物料</span>
          <FormItem
            prop="firstMaterial"
            :rules="{required: true,message:'选择物料',trigger: 'change'}"
          >
            <Select
              v-model="addTaskForm.firstMaterial"
              placeholder="选择物料"
              @on-change="changeMaterial()"
              class="min-width"
            >
              <template v-for="(material,index) in materialListSelect">
                <Option
                  :key="index"
                  :value="material.firstMaterial"
                >{{material.firstMaterial}}</Option>
              </template>
            </Select>
          </FormItem>
          </Col>
        </Row>
        <template v-for="(item, index) in addTaskForm.tasks">
          <Row
            :gutter="10"
            type="flex"
            justify="start"
            align="middle"
            class="row-top-margin"
          >
            <Col
              :md="6"
              class="entery-item"
            >
            <span>{{item.secondMaterial}}</span>
            <FormItem :prop="'tasks.'+index+'.materialCount'">
              <InputNumber
                v-model="item.materialCount"
                :min="0"
              ></InputNumber>
            </FormItem>
            </Col>
            <Col :md="5">
            <FormItem :prop="'tasks.'+index+'.finishTime'">
              <DatePicker
                v-model="item.finishTime"
                type="date"
                :clearable="false"
                format="yyyy-MM-dd"
                placeholder="完成日期"
              ></DatePicker>
            </FormItem>
            </Col>
            <Col :md="4">
            {{index}}
            <Upload
              ref="upload"
              multiple
              :action="uploadUrl"
              :data="{
                'imgIndex':index
              }"
              :before-upload="handleUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :headers="headerUpload"
              :on-progress="handleProgress"
              :show-upload-list="false"
              :max-size="51200"
              name="files"
            >
              <Button @click="uploadBtn(index)">上传文件</Button>
            </Upload>
            </Col>
            <Col :md="9">

            <template v-for="(info,infoIndex) in addTaskForm.tasks[index].imgInfos">
              <div class="pic-name">
                {{info.name}}
                <span
                  class="pic-loading"
                  v-if="info.status === '1'"
                >上传中</span>
                <span
                  class="pic-success"
                  v-if="info.status === '2'"
                >完成</span>
                <span
                  class="pic-error"
                  v-if="info.status === '3'"
                >上传失败</span>
                <span
                  class="pic-close"
                  @click="handleRemove(index,info,infoIndex)"
                >
                  X
                </span>
              </div>
            </template>
            </Col>
          </Row>
          </FormItem>
        </template>

        <FormItem>
          <div class="entry-btn-box">
            <Button @click="resetForm('addTaskForm')">清空</Button>
            <Button
              type="primary"
              @click="handleSubmitAddTasks('addTaskForm')"
              style="margin-left: 8px"
            >提交录入</Button>
            <span class="tips">(*文件不可超过50MB)</span>
          </div>
        </FormItem>
      </Form>

    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { fetchTaskAddContent, fetchAddTask } from "@/api/table";
import { Pagetitle } from "@/components";
import format from "date-format";
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      pageTitle: {
        title: "任务录入>" + this.$route.query.brandName
      },
      costCenterSelect: [],
      materialListSelect: [],
      secondListSelect: [],
      index: 1,
      addTaskForm: {
        costCenterId: "",
        firstMaterial: "",
        tasks: [
          // {
          //   brandId: "",
          //   userId: "",
          //   costCenterId: "",
          //   materialId: "",
          //   materialCount: 0,
          //   finishTime: "",
          //   imgInfos：[]
          // }
        ]
      },

      //上传
      uploadBtnIndex: "",
      fileList: []
    };
  },
  components: {
    Pagetitle
  },
  mounted() {
    this.getTaskAddContent();
  },
  methods: {
    btnFun() {
      this.addBrandModal = true;
    },
    async getTaskAddContent() {
      const res = await fetchTaskAddContent({
        userId: this.userId
      });
      this.costCenterSelect = [];
      this.materialListSelect = [];
      res.data.brandList.forEach(item => {
        const numberRoute = parseInt(this.$route.query.brandId);
        if (item.id === numberRoute) {
          item.costCenterList.forEach(cost => {
            const data = {};
            data.costId = cost.id;
            data.costCenterName = cost.costCenterName;
            this.costCenterSelect.push(data);
          });
        }
      });
      res.data.materialList.forEach(item => {
        const data = {};
        data.firstMaterial = item.firstMaterial;
        data.secondMaterialList = item.secondMaterialList;
        this.materialListSelect.push(data);
      });
      this.changeMaterial();
    },
    //通过物料循环表单
    changeMaterial() {
      this.materialListSelect.forEach(item => {
        if (this.addTaskForm.firstMaterial === item.firstMaterial) {
          this.addTaskForm.tasks = [];
          item.secondMaterialList.forEach(second => {
            const data = {};
            data.materialId = second.id;
            data.secondMaterial = second.secondMaterial;
            data.materialCount = 0;
            data.finishTime = "";
            data.imgInfos = [];
            this.addTaskForm.tasks.push(data);
          });
        }
      });
    },
    async addTask() {
      const upData = this.addTaskForm.tasks;
      let newUpData = [];
      let doAdd = false;
      upData.forEach(item => {
        const data = {};
        data.brandId = this.$route.query.brandId;
        data.userId = this.userId;
        data.costCenterId = this.addTaskForm.costCenterId;
        data.materialId = item.materialId;
        data.materialCount = item.materialCount;
        data.finishTime = format("yyyy-MM-dd", new Date(item.finishTime));
        const imgList = [];
        item.imgInfos.forEach(info => {
          if (info.url) {
            imgList.push(info.url);
          }
        });
        data.fileUrls = imgList.toString();
        if (data.materialCount > 0 && data.finishTime !== "NaN-NaN-NaN") {
          newUpData.push(data);
        }
      });
      if (newUpData.length > 0) {
        const res = await fetchAddTask(newUpData);
        if (res.status === 200) {
          this.resetForm("addTaskForm");
          this.$Message.success("提交成功");
        }
      } else {
        this.$Message.error("填写正确信息");
      }
    },
    resetForm(name) {
      this.$refs[name].resetFields();
      this.addTaskForm.tasks = [];
    },
    handleSubmitAddTasks(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.addTask();
        }
      });
    },
    //上传
    uploadBtn(index) {
      this.uploadBtnIndex = index;
    },
    handleUpload(file) {
      const imgInfo = {};
      imgInfo.name = file.name;
      imgInfo.status = "1";
      imgInfo.url = "";
      this.addTaskForm.tasks[this.uploadBtnIndex].imgInfos.push(imgInfo);
    },
    handleProgress(event, file, fileList) {},
    handleSuccess(res, file, fileList) {
      if (res.status !== 500) {
        const imgIndex = res.data.imgIndex;
        const newImg = res.data.url;
        const infos = this.addTaskForm.tasks[imgIndex].imgInfos;
        for (let i = 0; infos.length > i; i++) {
          if (infos[i].name === file.name) {
            infos[i].status = "2";
            infos[i].url = newImg;
          }
        }
      } else {
        this.$Message.error("文件上传失败");
      }
    },
    handleError(file) {
      this.$Message.error("文件不符合要求");
    },
    //物料index,图片信息,图片index
    handleRemove(index, info, infoIndex) {
      this.addTaskForm.tasks[index].imgInfos.map((item, itemIndex) => {
        if (item.name === info.name) {
          this.addTaskForm.tasks[index].imgInfos.splice(itemIndex, 1);
        }
      });
    }
  },
  computed: {
    ...mapGetters(["userId"]),
    uploadUrl: () => {
      return process.env.BASE_URL + "file/upload";
    },
    headerUpload: () => {
      const data = {};
      data.token = getToken();
      return data;
    }
  }
};
</script>
<style lang="less" scoped>
@import "~@/styles/mixin";
.row-border-bottom {
  margin: 0 100px;
  border-bottom: 1px solid #bdbdbd;
}
.row-top-margin {
  margin-top: 20px;
}
.min-height {
  min-height: calc(78vh);
}
.pic-loading {
  color: #cb2d00;
}
.pic-success {
  color: #71ce3b;
}
.pic-name {
  display: inline-block;
  margin: 3px 3px;
}
.pic-close {
  display: inline-block;
  margin-left: 5px;
  cursor: pointer;
}
.pic-close:hover {
  color: #cb2d00;
}
.seconditem {
  &-name {
    font-size: 16px;
    font-family: SourceHanSansCN-Medium, SourceHanSansCN;
    color: @default-color;
    margin-bottom: 10px;
  }
}
.entery-top {
  display: flex;
  align-items: center;
  span {
    font-size: 16px;
    color: #222121;
    margin-right: 14px;
    margin-bottom: 24px;
    font-weight: 500;
  }
}
.entery-item {
  display: flex;
  align-items: center;
  span {
    text-align: right;
    width: 150px;
    color: #222121;
    margin-right: 14px;
    margin-bottom: 24px;
  }
}
.min-width {
  min-width: 208px;
}
.entry-btn-box {
  margin-top: 110px;
  text-align: center;
  .ivu-btn {
    width: 160px;
    height: 46px;
    font-size: 16px;
  }
  .tips {
    display: inline-block;
    height: 46px;
    margin-left: 14px;
    color: @primary-color;
  }
}
.ivu-upload {
  margin-bottom: 24px;
  align-items: center;
}
</style>
<style>
.ivu-progress {
  display: none;
}
</style>